import {MyNavBar, ShowLoading} from '@/components'

import './index.less'
import {useListHook} from '@/hooks'
import {_getFollow, _delFollow, _postFollow} from './store'
import {history} from 'umi'
import {BsHeart, BsHeartFill} from 'react-icons/bs'
import {useEffect, useState} from 'react'
import {Toast} from 'antd-mobile'

function Follow() {
  const {data, showLoading} = useListHook({func: _getFollow})

  const [ tempData, setTempData ] = useState(null)

  const [ isFirst, setIsFirst ] = useState(true)

  useEffect(() => {
    if (isFirst) {
      setTempData(data.map(item => ({...item, isFollow: true})))
      setIsFirst(false)
    } else {
      const temp = []
      for (let i = 0, len = data.length; i < len; i++) {
        if (tempData[i] && !tempData[i].isFollow) {
          temp.push(tempData[i])
        } else {
          temp.push({...data[i], isFollow: true})
        }
      }
      setTempData(temp)
    }
  }, [ data ])

  const handleClick = async (id, isFollow, index) => {
    let result = null
    if (isFollow) {
      result = await _delFollow(id)
    } else {
      result = await _postFollow(id)
    }
    if (result) {
      Toast.success('操作成功')
      const temp = JSON.parse(JSON.stringify(tempData))
      temp[index].isFollow = !temp[index].isFollow
      setTempData(temp)
    }
  }

  return (
    <div>
      <MyNavBar title='我的关注'/>
      <div className='follow'>
        {tempData?.length ? tempData.map((item, index) => (
          <div className='follow-item' onClick={() => {
            history.push({pathname: '/user/userDetail', query: {id: item?.followId}})
          }}>
            <div className='header'>
              <img src={item?.followUserUserInfoAvatar || require('@/assets/user.png')}/>
              <p className='name'>{item?.followUserNickName}</p>
              <div className='btn-heart'>
                <span onClick={(e) => {
                  e.stopPropagation()
                  handleClick(item?.followId, item?.isFollow, index)
                }}>
                  {item?.isFollow ? <BsHeartFill /> : <BsHeart/>}
                </span>
              </div>
            </div>
          </div>
        )) : ''}
        <ShowLoading showLoading={showLoading}/>
      </div>
    </div>
  )
}

export default Follow
